﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model;
using System.Text;
using System.Configuration;
using System.Security.Cryptography;

namespace OA.Controllers
{
    public class MemberSaleController : Controller
    {
        //
        // GET: /MemberSale/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult MemberSale()
        {
            memberInfoManager manger = new memberInfoManager();
            memberInfo mInfo = new memberInfo();
            string memberId = System.Web.HttpContext.Current.Request.QueryString["memberId"];
            if (!string.IsNullOrEmpty(memberId))
            {
                
                mInfo = manger.GetModel(memberId);
                if (mInfo.status != 0) 
                {
                    return Content("<script>alert('此卡无法消费');window.parent.location.href='/Loading/Index/?src=/Desktop/Index/';parent.layer.close(parent.layer.getFrameIndex());</script>");
                }
                ViewData["memberId"] = mInfo.memberId;
                ViewData["point"] = mInfo.point;
                ViewData["balance"] =Convert.ToDecimal(mInfo.Balance).ToString("#0.00");
                ViewData["memberName"] = mInfo.memberName;
            }
            if (Session["memberId"] != null)
            {
                mInfo = manger.GetModel(Session["memberId"].ToString());
                if (mInfo.status != 0)
                {
                    return Content("<script>alert('此卡无法消费');window.location.href='/Loading/Index/?src=/Desktop/Index/';</script>");
                }
                ViewData["memberId"] = mInfo.memberId;
                ViewData["point"] = mInfo.point;
                ViewData["balance"] = Convert.ToDecimal(mInfo.Balance).ToString("#0.00");
                ViewData["memberName"] = mInfo.memberName;
            }
            goodsManager gM = new goodsManager();
            List<goods> gModel = gM.GetAll().ToList();
            if (gModel.Count > 0)
            {
                return View(gModel);

            }
            return View();
        }

        // 会员消费中根据id获取商品 
        public ActionResult AddGoods(FormCollection fc)
        {


            if (fc["Sindex"] != "" && fc["Sindex"] != string.Empty)
            {
                goodsManager gM = new goodsManager();
                goods gs = new goods();
                string x = fc["Sindex"];
                int id = Convert.ToInt32(fc["Sval"]);
                gs = gM.GetByID(id);
                return Content(gs.goodsName + "|" + gs.price + "|" + gs.goodsId);

            }
            return View();
        }


        //套餐情况
        public ActionResult TaoCan(FormCollection fc)
        {
            string toptr ="<tr class=\"DGHeaderStyle\"><td>商品名称</td><td>数量</td><td>单位</td><td>操作</td></tr>";
             goods gS = new goods();
            goodsManager gsManager=new goodsManager();
            taocanjilu TJ = new taocanjilu();
            taocanjiluManager tjManager = new taocanjiluManager();
            StringBuilder sb = new StringBuilder();
            string memberId = fc["memberId"];
            TJ = tjManager.getByMemberId(memberId);
            if (TJ == null)
            {
                return Content(toptr);
            }
            sb.Append(toptr);
            if (TJ.xiangqing != null)
            {
                if (TJ.xiangqing != "" && TJ.xiangqing != null)
                {
                    string[] liebiao = TJ.xiangqing.Split('|');
                    for (int i = 0; i < liebiao.Length; i++)
                    {
                        if (liebiao[i] == "")
                        {
                            continue;
                        }
                        string[] liebiaoxiangqing = liebiao[i].Split(',');
                        Model.goods goodmodle = gsManager.getBygoodsId(liebiaoxiangqing[0]);
                        if (goodmodle == null)
                        {
                            continue;
                        }
                        
                       // sb.Append("<tr><td>"+liebiaoxiangqing[0]+"</td>");
                        sb.Append("<td>"+goodmodle.goodsName+"</td>");
                        sb.Append("<td>" + liebiaoxiangqing[1] + "</td>");
                        sb.Append("<td>" + goodmodle.unit + "</td>");
                        sb.Append("<td><input type=\"button\" value=\"兑换\" class=\"button2\" onclick=\"DH(this);\"></td>");
                        sb.Append("</tr>");
                    }
                }
            }
            return Content(sb.ToString());

        }

        //结算
        public ActionResult MemberAccount(FormCollection fc)
        {
            wasteBook WB = new wasteBook();
            goodsInfo GI = new goodsInfo();
            memberInfo MI = new memberInfo();
            
            wasteBookManager WBManager = new wasteBookManager();
            goodsInfoManager GIManager = new goodsInfoManager();
            memberInfoManager MIManger = new memberInfoManager();
            string memberId = fc["memberId"];
            string memberCardId = fc["memberCardId"];
            int discount = Convert.ToInt32(fc["discount"]);
            decimal sale=decimal.Parse(fc["sale"]);
            decimal cardPay = decimal.Parse(fc["cardPay"]);
            decimal carhPay = decimal.Parse(fc["carhPay"]);
            decimal discountAmount=decimal.Parse(fc["discountAmount"]);
            string meiZu=fc["meiZu"];
            string jiedairen = fc["jiedairen"];
            string pwd = fc["pwd"];
            if (meiZu != "")
            {
                MI = MIManger.GetModel(memberId);
                string statusName = "";
                switch (MI.status)
                {
                    case 0: statusName = "正常";
                        break;
                    case 1: statusName = "挂失";
                        break;
                    case 2: statusName = "停用";
                        break;
                    default: break;
                }
                consumeSolutionManager CSManager = new consumeSolutionManager();
                consumeSolution cs = CSManager.GetByID(Convert.ToInt32(MI.cardType));
                string cardTypeName = "";
                if (cs != null)
                {
                    cardTypeName = cs.solutionName;
                }

                string sexName = "";
                if (Convert.ToBoolean(MI.sex))
                { 
                    sexName = "男";
                }
                else
                { 
                    sexName = "女";
                }
               MD5 md5 = new MD5CryptoServiceProvider();
               byte[] bt = Encoding.Default.GetBytes(pwd);
               bt = md5.ComputeHash(bt);
               string con_pwd= BitConverter.ToString(bt).Replace("-", "");
               if (MI.pwd == null)
               {
                   if (!string.IsNullOrEmpty(pwd))
                   { 
                       return Content("密码有误");
                   }
               }
               else
               {
                   if (MI.pwd != con_pwd)
                   {
                       return Content("密码有误,请重新输入密码");
                   }
               } 
                WB.terminalId = 0;
                WB.operatorId = "admin";
                WB.memberCardId = memberCardId;
                WB.date = DateTime.Now;
                WB.consumeType = MI.cardType;
                WB.consumeTimes = 0;
                if(discountAmount>0)
                {
                  WB.consumeMoney=discountAmount;
                  
                }
                else
                {
                    WB.consumeMoney = sale;
                }
                WB.cardPayMoney = cardPay;
                WB.cashPayMoney = carhPay;
                if (carhPay > 0)
                {
                    WB.cardBalance = 0;
                }
                else 
                {
                    WB.cardBalance = MI.Balance - WB.consumeMoney;
                }
                WB.refundmentMoney = 0;
                WB.refundmentIntegral = 0;
                WB.exchangeIntegral = 0;
                WB.consumeIntegral = 0;
                WB.totalIntegral = 0;
                WB.savingMoney = 0;
                WB.details = ConfigurationManager.AppSettings["details"];
                WB.Discount = discount;
                WB.jiedairen = jiedairen;
                WBManager.Add(WB);
                WBManager.Update();
                string[] meizuGoods = meiZu.Split('|');
                for (int i = 0; i < meizuGoods.Length-1; i++)
                {
                    goods GS = new goods();
                    goodsManager GSManager = new goodsManager();
                    string[] goods = meizuGoods[i].Split(',');
                    GI.gid = GSManager.getBygoodsName(goods[0]).goodsId;
                    GI.goodsprice =decimal.Parse(goods[1]);
                    GI.goodscount =int.Parse(goods[2]);
                    GI.selltime = DateTime.Now;
                    GI.zhekou = discount;
                    GI.wasteBookId = WB.id;
                    GIManager.addMore(GI) ;
                }
                if (carhPay > 0)
                {
                    MI.Balance = 0;
                }
                else
                {
                    MI.Balance = MI.Balance - WB.consumeMoney;
                }
                string[] ModelArray = new string[] { MI.memberId, cardTypeName, MI.memberName, sexName, statusName, MI.createDate.ToString(), MI.expiresDate.ToString(), "0", "0", "0", sale.ToString(), "0", "0", "0", "0", "0" };
                string go = printX(ModelArray, MI.cardType);
                MIManger.Update();
                //"alert('消费成功');closeWindows()"
                return Content(go);
            }
               
            return View();
        }
        public string printX(string[] ModelArray, int cardTypeId)
        {
            cardTemplates ct = new cardTemplates();
            memberInfo m = new memberInfo();
            //Model.memberInfo mo = m.GetUserIdMode(id); 
            consumeSolution cs = new consumeSolution();
            cardTemplates cts = new cardTemplates();
            consumeSolutionManager csManager = new consumeSolutionManager();
            cardTemplatesManager ctsManager = new cardTemplatesManager();
            var csName = csManager.GetByID(cardTypeId);
            string solutonName = csName.solutionName;
            var cardID = csName.cardTemplateId;
            var card = ctsManager.GetByID(Convert.ToInt32(cardID));
            string cardTempName = card.template;
            //   Model.memberInfo mode = GetModel(); 
            cardTempName = cardTempName.Replace("\n", "#");
            string[] users = cardTempName.Split('#');
            string muban = "会员卡号#卡片类型#会员姓名#性　　别#卡片状态#办卡日期#截止日期#累计积分#本次积分#可用积分#本次消费#储值余额#折扣金额#本次充值#积分支付#现金消费#空　　行";

            string[] mubanArray = muban.Split('#');

            string[] ModelArray1 = ModelArray;
            string a = users.Length.ToString();

            string t = "";

            for (int i = 0; i < users.Length; i++)
            {

                t += users[i];
                for (int j = 0; j < mubanArray.Length - 1; j++)
                {
                    if (users[i] == mubanArray[j])
                    {
                        t += ":" + ModelArray[j];

                    }

                }
                t += "\n";
            }

            string content = t.Replace("空　　行", "");
            return content;

        }
    }
}
